package com.borrowed.book.system.controller;

import com.borrowed.book.system.domain.AjaxResult;
import com.borrowed.book.system.domain.PageDomain;
import com.borrowed.book.system.domain.TableDataInfo;
import com.borrowed.book.system.util.Convert;
import com.borrowed.book.system.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.awt.geom.RectangularShape;
import java.util.List;

/**
 * web层通用处理
 */
public class BaseController {


    /**
     * 启动分页
     */
    protected void startPage(){
        PageDomain pageDomain=getDomain();
        Integer pageNum=pageDomain.getPageNum();
        Integer pageSize=pageDomain.getPageSize();
        if(StringUtils.isNotNull(pageNum)&&StringUtils.isNotNull(pageSize)){
            String orderBy=pageDomain.getOrderBy();
            PageHelper.startPage(pageNum,pageSize,orderBy);
        }
    }

    /**
     * 获取分页返回数据
     * @return
     */
    protected TableDataInfo getDataTable(List<?> list){
        TableDataInfo rspData=new TableDataInfo();
        rspData.setCode(200);
        rspData.setData(list);
        rspData.setMsg("操作成功");
        rspData.setCount(new PageInfo(list).getTotal());
        return rspData;
    }

    /**
     * 返回错误结果
     * @return
     */
    protected  TableDataInfo getErrorInfo(String errorMsg){
        TableDataInfo rspData=new TableDataInfo();
        rspData.setCode(500);
        rspData.setMsg(errorMsg);
        return rspData;
    }



    protected PageDomain getDomain(){
        PageDomain pageDomain=new PageDomain();
        pageDomain.setPageNum(Convert.toInt(getRequest().getParameter("page")));
        pageDomain.setPageSize(Convert.toInt(getRequest().getParameter("limit")));
        pageDomain.setSort(getRequest().getParameter("sort"));
        pageDomain.setOrderByColumn(getRequest().getParameter("orderByColumn"));
        return pageDomain;
    }


    protected ServletRequestAttributes getRequestAttributes(){
        RequestAttributes attributes= RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) attributes;
    }

    protected HttpServletRequest getRequest(){
        return getRequestAttributes().getRequest();
    }

}
